﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SSActionManager : MonoBehaviour
{
    // 动作集
    private Dictionary<int, SSAction> actions = new Dictionary<int, SSAction>();
    // 等待执行的动作的list
    private List<SSAction> waitingTodo = new List<SSAction>();
    // 等待删除的动作的key list
    private List<int> waitingDelete = new List<int>();

    protected void Update()
    {
        // 将等待执行list中的动作保存进动作集
        foreach (SSAction ac in waitingTodo)
            actions[ac.GetInstanceID()] = ac;
        waitingTodo.Clear();

        // 运行被保存的动作
        foreach (KeyValuePair<int, SSAction> kv in actions)
        {
            SSAction ac = kv.Value;
            if (ac.destroy)
            {
                waitingDelete.Add(ac.GetInstanceID());
            }
            else if (ac.enable)
            {
                ac.Update();
            }
        }

        // 销毁等待删除list中的动作
        foreach (int key in waitingDelete)
        {
            SSAction ac = actions[key];
            actions.Remove(key);
            Destroy(ac);
        }
        waitingDelete.Clear();
    }

    // 准备执行一个动作，将动作初始化，并加入到等待执行list
    public void RunAction(GameObject gameObject, SSAction action, ISSActionCallback manager)
    {
        action.gameObject = gameObject;
        action.transform = gameObject.transform;
        action.callback = manager;
        waitingTodo.Add(action);
        action.Start();
    }
    
    protected void Start()
    {

    }

}
